<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Nohost</title>
    <style>
      html, body {
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
      }
      .disabled .action-btn {
        color: #ccc;
        cursor: not-allowed;
      }
      main {
        text-align: center;
        width: 200px;
        height: 80px;
        position: absolute;
        top: 50%;
        left: 50%;
        margin: -40px 0 0 -100px;
      }
      main button {
        width: 180px;
        height: 46px;
        font-size: 20px;
      }
      main button {
        background-color: #fe9455;
        color: #fff;
        border: none;
        border-radius: 2px;
        cursor: pointer;
        outline: none;
      }
      main button[disabled] {
        background-color: #ccc!important;
      }
      main button:hover {
        background-color: #f3803b;
      }
      main button:active {
        background-color: #ee7946;
      }
      main.enabled button {
        background-color: #188eee;
      }
      main.enabled button:hover {
        background-color: #147de2;
      }
      main.enabled button:active {
        background-color: #1774c9;
      }
      .action-bar {
        margin-top: 15px;
      }
      .action-bar a {
        margin: 0 8px;
      }
    </style>
    <script>
      window.onbeforeunload = () => '';
    </script>
    <script>
      const { shell, ipcRenderer, remote } = require('electron');

      const $ = (id) => {
        return document.getElementById(id);
      };

      const isDisabled = () => {
        return $('main').className === 'disabled' || $('switchProxy').disabled;
      };

      // 注册 Handlers
      let settingsWin;
      const openSettings = () => {
        if (isDisabled()) {
          return;
        }
        if (!settingsWin || settingsWin.closed) {
          settingsWin = window.open('http://local.wproxy.org/', null, 'width=10000,height=10000');
        }
        settingsWin.focus();
      };
      ipcRenderer.on('openSettings', openSettings);

      let selectEnvWin;
      const openSelectEnv = () => {
        if (isDisabled()) {
          return;
        }
        if (!selectEnvWin || selectEnvWin.closed) {
          selectEnvWin = window.open('http://local.wproxy.org/whistle.nohost-client/', null, 'width=1200,height=800');
        }
        selectEnvWin.focus();
      };
      ipcRenderer.on('openSelectEnv', openSelectEnv);

      const openHelp = () => {
        shell.openExternal('https://nohosts.github.io/nohost/');
      };
      ipcRenderer.on('openHelp', openHelp);

      const closeAllChildWindow = () => {
        if (settingsWin && !settingsWin.closed) {
          settingsWin.close();
        }
        if (selectEnvWin && !selectEnvWin.closed) {
          selectEnvWin.close();
        }
      };
    </script>
  </head>
  <body>
    <main id="main" class="disabled">
      <button id="switchProxy" onclick="switchProxy()">启用</button>
      <div class="action-bar">
        <a class="action-btn" href="javascript:;" onclick="openSettings()">设置</a>
        <a class="action-btn" href="javascript:;" onclick="openSelectEnv()">选择环境</a>
        <a href="javascript:;" onclick="openHelp()">帮助</a>
      </div>
    </main>
    <script>
      const { enableProxy, disableProxy, proxyEnable } = require('./lib');
      const btn = $('switchProxy');
      const main = $('main');
      const platform = require('electron').remote.require('os').platform();

      const switchProxy = () => {
        if (btn.disabled) {
          return;
        }
        btn.disabled = true;
        if (main.className === 'enabled') {
          return disableProxy().then(() => {
            btn.disabled = false;
            main.className = 'disabled';
            btn.innerHTML = '启用';
            closeAllChildWindow();
            ipcRenderer.send('switchProxy', false)
          }).catch((e) => {
            btn.disabled = false;
            alert('操作失败，请稍后重试。');
            throw e;
          });
        }

        return enableProxy().then(() => {
            btn.disabled = false;
            main.className = 'enabled';
            btn.innerHTML = '关闭';
            ipcRenderer.send('switchProxy', true)
        }).catch((e) => {
            btn.disabled = false;
            alert('操作失败，请稍后重试。');
            throw e;
          });
      };
      ipcRenderer.on('switchProxy', switchProxy);

      const ensureProxyEnable = async () => {
        if (!btn.disabled && main.className === 'enabled' && !(await proxyEnable())) {
          main.className = 'disabled';
          btn.innerHTML = '启用';
          await switchProxy();
        }
        setTimeout(ensureProxyEnable, 10000);
      };
      const closeWindow = () => {
        window.close();
        if (platform === 'darwin')
          remote.app.quit();
      };

      const init = async () => {
        try {
          await enableProxy();
          btn.disabled = false;
          main.className = 'enabled';
          btn.innerHTML = '关闭';
          ipcRenderer.send('switchProxy', true);
        } catch (e) {
          if (confirm('启动失败，是否重试？')) {
            return await init();
          }
        }
        await ensureProxyEnable();
        window.onbeforeunload = (e) => {
          if (!btn.disabled && main.className === 'disabled') {
            return;
          }
          process.nextTick(() => {
            if (platform === 'darwin') {
              remote.app.show();
            }
            remote.app.focus();
            remote.require('electron').dialog.showMessageBox({
                type: 'question',
                message: '退出后将不能使用Nohost，确定退出？',
                buttons: ['取消', '退出', '最小化'],
                defaultId: 2
              }).then(({ response }) => {
                switch (response) {
                  case 0: e.preventDefault(); break;
                  case 1: switchProxy().then(closeWindow, closeWindow); break;
                  case 2: {
                    if (platform === 'darwin') {
                      remote.app.hide();
                    } else if (platform === 'win32') {
                      remote.getCurrentWindow().hide();
                    }
                    break;
                  }
                }
              });
          });
          return '';
        };
      };
      init();
    </script>
  </body>
</html>
